"""
i = 0
while True:
    print(i) # 重复这一个过程，不算迭代
"""
# 迭代是一重复的过程，每一次重复都基于上一次的结果而来
# l = ['a','b','c']
# i = 0
"""
while i<len(l):
    print(i) # 打印索引
    print(l[i]) # 根据索引取值
    i +=1 # 循环变量，不能丢，每次递增
"""
# 哪些数据类型需要这样迭代取值？
# 字符串、列表、元组、集合
"""
for i in "test01":
    print(i)
    # 
    # t
    # e
    # s
    # t
    # 。。
    
for i in [10,20,30]:
    print(i)
for i in (10,20,30):
    print(i)
for i in {10,20,30}:
    print(i)
"""
"""
dic = {"name":"dahai","age":18}
for i in dic:
    print(i)
"""

# 支持__iter__()方法的，都可以迭代
"""
a = 1
# a.__iter__() # 没有这个方法
b = 1.1
# b.__iter__() # 没有
c = "hello"
c.__iter__() # 有
d = [10,20,30]
d.__iter__()
e = {10,20,30}
e.__iter__()
f = (10,20,30)
f.__iter__()
g = {"a":"b"}
g.__iter__()
"""

dic = { 'x ':1, 'y':2,'z': 3} # x y z
a = dic.__iter__() # 创建了一个迭代器
"""
iter和next被称为迭代器协议
"""
"""
print(a.__next__()) # x
print(a.__next__()) # y
print(a.__next__()) # z
print(a.__next__()) # 取空了就会报错：StopIteration
"""
# 误区
# print(dic.__iter__().__next__()) # x
# print(dic.__iter__().__next__()) # x 为什么不是y呢？

"""
for i in "test01":
    # iter() next() for循环底层做了这两件事儿
    print(i)
"""
dic = { 'x':1,'y' :2,'z':3}
iter_dic = dic.__iter__()
"""
print(next(iter_dic)) # next等同于__next__() x
print(next(iter_dic)) # next等同于__next__() y
print(next(iter_dic)) # next等同于__next__() z
print(next(iter_dic)) # 报错
"""
"""
while True:
    try:
        print(next(iter_dic))
    except:
        print("取完了")
        break
for i in "test01":
    # iter() next() for循环底层做了这两件事儿
    # 异常捕获，最后一个不报错
    print(i)

"""

# 生成器 yield
# 会先执行函数本身的代码块，然后再次走到yield方法里return返回
def sum_num():
    n = 0 # 定义的n是0开始
    while True: # while True循环
        yield n # 相当于return 返回
        n += 1 # 下次调用的时候，先执行它

a1 = sum_num() # 这里的a1就相当于是地址值
print(a1) # <generator object sum_num at 0x0000020DF9F59580>
print(next(a1)) # 第一次的时候是0
print(next(a1)) # 第二次的时候是1
print(next(a1)) # 第三次的时候是2

"""
生成器也是迭代器的一种，但它只可以迭代一次
"""



def eat():
    print("吃东西")
    yield print("吃什么")
a1 = eat()
next(a1)
next(a1)











